<?php

namespace app\modules\cruise\controllers;

use Yii;
use app\modules\cruise\models\CustomerCheck;
use app\modules\cruise\models\CustomerCheckSearch;
use Overtrue\Pinyin\Pinyin;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\filters\AccessControl;

/**
 * CheckController implements the CRUD actions for CustomerCheck model.
 */
class CheckController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        //'actions' => ['list', 'index','create','view','update','delete'],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all CustomerCheck models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CustomerCheckSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single CustomerCheck model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new CustomerCheck model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new CustomerCheck();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }else{
            $model->gender = 1;
            $model->passport_check = 1;
            $model->country = '中国';
            return $this->render('create', [
                'model' => $model,
            ]);
        }

        
    }

     // 获取文字拼音
    public function actionPinyin(){//{{{

        $name = Yii::$app->request->get("name");

        $pinyin = new Pinyin();

        $ret = $pinyin->sentence($name);

        print_r(str_replace(' ', '', strtoupper($ret)));
    }//}}}

    // 生成护照截止日期
    public function actionPassport(){//{{{
        
        $passport = Yii::$app->request->get("passport");
        $date = strtotime($passport);

        $year = strtotime("+10 year", $date);   // 十年
        $day = strtotime("-1 day", $year);      // 一天前
        
        print_r(date("Y-m-d", $day));
    }//}}}

    /**
     * Updates an existing CustomerCheck model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing CustomerCheck model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the CustomerCheck model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return CustomerCheck the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = CustomerCheck::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }


    //导入人员信息
    public function actionImportCut(){
        // header("Content-type:text/html; charset=utf-8");
        // $path = sprintf('%s/web/cut2.xlsx', Yii::$app->basePath);
        $path = $this->upload_excel();

        $data = $this->getData($path);
       
        $data_arr = [];
        
        if($data['data']){
            $data_arr = $data['data'];
        }
      
        $gender_en = [
            '男' => 1,
            '女' => 2,
        ];
        $province_2 = \yii::$app->params['area']['country_code_2'];
        $province_2 = array_flip($province_2);
        //导入数据
        $transaction = Yii::$app->db->beginTransaction();
        try{

            foreach($data_arr as $key=>$varr){
                $customer = new CustomerCheck();
                $customer->first_name = $varr['B'];
                $customer->last_name = $varr['C'];
                $customer->en_first_name = $varr['D'];
                $customer->en_last_name = $varr['E'];
                $customer->gender = isset($gender_en[$varr['F']]) ?$gender_en[$varr['F']] : 1;
                $customer->country = isset($province_2[$varr['C']]) ? $province_2[$varr['C']] : '中国';
                $customer->birthday = $varr['H'];
                $customer->native = $varr['I'];
                $customer->passport = $varr['J'];
                $customer->passport_add = $varr['K'];
                $customer->passport_grant = $varr['L'];
                $customer->passport_date = $varr['M'];
                $customer->passport_check = 1;

                if($customer->save()){

                }else{
                    $transaction->rollBack();
                    $errors = $customer->getErrors();
                    //获取第一条错误信息
                    $message = '';
                    $firstError = is_array($errors) ? array_shift($errors) : '';
                    $message = is_array($firstError) ? array_shift($firstError) : '';
                    
                    print_r(json_encode(['code'=>'error','message'=>'第'.$key.'行信息有误( '.$message.'),请修改后重新导入']));
                    return false;
                }
                      
            }

            $transaction->commit();
            
        }catch(\Exception $e){
            $transaction->rollBack();
            throw $e;
        }

        print_r(json_encode(['code'=>'ok','message'=>'导入成功!']));
       
    }

    //上传文件
    private function upload_excel(){

        $upload = UploadedFile::getInstanceByName('excel');
        if($upload){
            $suffix = $upload->extension;
            $dir = sprintf("uploads/excel/%s", date("Ym"));
             
            if(!is_readable($dir)) {
                is_file($dir) or mkdir($dir,0755);  
            }  

            $path = sprintf('%s/%s.%s', $dir, uniqid(true), $suffix);

            if($upload->saveAs($path)){
                return $path;
            }
        }else{
            return false;
        }

    }


    //获取excel 数据
    private function getData($filePath){//{{{
        if(empty($filePath)){
            return [];
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();

        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new \PHPExcel_Reader_Excel5();
        }

        if(!$PHPReader->canRead($filePath)){
            return ;
        }

        $PHPExcel = $PHPReader->load($filePath);

        $currentSheet = $PHPExcel->getSheet(0);

        $allRow = $currentSheet->getHighestRow();
  
        $arrExcel = []; //数据
    
        for($rowIndex = 2;$rowIndex <= $allRow; $rowIndex++){
            
            for($colIndex='A';$colIndex<='M';$colIndex++){
                $addr = $colIndex.$rowIndex;
               
                $cell = $currentSheet->getCell($addr)->getValue();
                
                if($cell instanceof PHPExcel_RichText){     //富文本转换字符串
                    $cell = $cell->__toString();
                }
                if(!empty($cell)){
                    $arrExcel['A'.$rowIndex][$colIndex]= trim($cell);
                }else{
                    $arrExcel['A'.$rowIndex][$colIndex]= '';
                }
                $cell = '';
            }

        }
      
        $data['data'] = $arrExcel; //数据
    
        return $data;

    }//}}}


}
